<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="姓名" style="width: 150px;" class="filter-item" @keyup.enter.native="handleFilter" />&nbsp;
      <el-select v-model="listQuery.school" placeholder="学校" clearable style="width: 150px" class="filter-item">
        <el-option v-for="item in schoolListOptions" :key="item" :label="item" :value="item" />
      </el-select>&nbsp;
      <el-select v-model="listQuery.major" placeholder="专业" clearable style="width: 150px" class="filter-item">
        <el-option v-for="item in majorListOptions" :key="item" :label="item" :value="item" />
      </el-select>&nbsp;
      <el-select v-model="listQuery.state" placeholder="状态" clearable class="filter-item" style="width: 150px">
        <el-option v-for="item in stateOptions" :key="item" :label="item" :value="item" />
      </el-select>&nbsp;
      <el-select v-model="listQuery.sort" style="width: 150px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>&nbsp;
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        Search
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        Add
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        Export
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="auto" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <!-- 学号 -->
      <el-table-column label="学号" width="auto" align="center">
        <template slot-scope="{row}">
          <span>{{ row.sno }}</span>
        </template>
      </el-table-column>

      <!-- 姓名 -->
      <el-table-column label="姓名" min-width="auto">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.name }}</span>
        </template>
      </el-table-column>

      <!-- 省份 -->
      <el-table-column label="籍贯" width="auto" align="center">
        <template slot-scope="{row}">
          <span>{{ row.location }}</span>
        </template>
      </el-table-column>

      <!-- 学校 -->
      <el-table-column label="学校" width="auto" align="center">
        <template slot-scope="{row}">
          <span>{{ row.school }}</span>
        </template>
      </el-table-column>
  
      <!-- 学院 -->
      <el-table-column label="学院" width="auto" align="center">
        <template slot-scope="{row}">
          <span>{{ row.academy }}</span>
        </template>
      </el-table-column>

      <!-- 专业 -->
      <el-table-column label="专业" width="auto" align="center">
        <template slot-scope="{row}">
          <span>{{ row.major }}</span>
        </template>
      </el-table-column>

      <!-- 年级 -->
      <el-table-column label="年级" width="auto" align="center">
        <template slot-scope="{row}">
          <span>{{ row.grade }}</span>
        </template>
      </el-table-column>

      <!-- 班级 -->
      <!-- <el-table-column label="班级" width="auto" align="center">
        <template slot-scope="{row}">
          <span>{{ row.myclass }}</span>
        </template>
      </el-table-column> -->

      <!-- 积分 -->
      <el-table-column label="积分" width="auto" align="center">
        <template slot-scope="{row}">
          <span>{{ row.points }}</span>
        </template>
      </el-table-column>

      <!-- 头像 -->
      <el-table-column label="头像" align="center" width="auto">
        <template slot-scope="{row}">
          <span >{{ row.image }}</span>
        </template>
      </el-table-column>

      <!-- 操作者 -->
      <el-table-column label="操作者" align="center" width="auto">
        <template slot-scope="{row}">
          <span>{{ row.update_user }}</span>
        </template>
      </el-table-column>

      <!-- 操作日期 -->
      <el-table-column label="操作日期" width="auto" align="center">
        <template slot-scope="{row}">
          <span>{{ row.update_time | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>

      <!-- 状态 -->
      <el-table-column label="状态" class-name="state-col" width="auto" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.state | stateFilter">
            {{ row.state }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 操作 -->
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            修改
          </el-button>
          <el-button v-if="row.state!='active'" size="mini" type="1" @click="handleModifystate(row,'active')">
            激活
          </el-button>
          <el-button v-if="row.state!='inactive'" size="mini">
            已激活
          </el-button>
          <el-button v-if="row.state!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getStudentList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="姓名" prop="name">
            <el-input v-model="temp.name" class="filter-item" placeholder=""></el-input>
        </el-form-item>
        
        <el-form-item label="学号" prop="sno">
          <el-input v-model="temp.sno" class="filter-item" placeholder=""></el-input>
        </el-form-item>

        <el-form-item label="学校" prop="school">
          <el-select v-model="temp.school"  class="filter-item" placeholder="请选择">
            <el-option v-for="item in schoolListOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>

        <el-form-item label="学院" prop="academy">
          <el-select v-model="temp.academy"  class="filter-item" placeholder="请选择">
            <el-option v-for="item in academyListOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>

        <el-form-item label="专业" prop="major">
          <el-select v-model="temp.major"class="filter-item" placeholder="请选择">
            <el-option v-for="item in majorListOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
  
        <el-form-item label="年级" prop="grade">
          <el-select v-model="temp.grade" class="filter-item" placeholder="请选择">
            <el-option v-for="item in gradeOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="班级" prop="myclass">
          <el-select v-model="temp.myclass" class="filter-item" placeholder="请选择">
            <el-option v-for="item in classOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item> -->

        <el-form-item label="籍贯" prop="location">
          <el-select v-model="temp.location" class="filter-item" placeholder="请选择">
            <el-option v-for="item in provinceOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>

        <el-form-item label="头像" prop="image">
          <Upload v-model="temp.image"></Upload>
        </el-form-item> 
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createStudentData():updateStudentData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import {fetchStudentList, createStudent, updateStudent } from '@/api/student'
import waves from '@/directive/waves'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import Upload from '@/components/Upload/SingleImage'

export default {
  name: 'ComplexTable',
  components: { Pagination, Upload },
  directives: { waves },
  filters: {
    stateFilter(state) {
      const stateMap = {
        active: '1',
        inactive: '0',
        deleted: 'danger'
      }
      return stateMap[state]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined, //姓名
        sno: undefined, //学号
        location: undefined, //籍贯
        sex: undefined, //性别
        school:'', //学校
        academy:'',//学院
        major: '', //专业
        grade:'',
        myclass: undefined, //班级
        id_number:undefined, //身份证号码
        admission_number:undefined, //录取通知书编号
        points: undefined, //获得的积分
        image:undefined,
        sort: '+id'
      },
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      stateOptions: ['active', 'inactive'],//激活状态
      schoolListOptions:  ['大学A','大学B','大学C','大学D','大学E','大学F','大学G','大学H',
                    '大学I','大学J','大学K','大学L','大学M','大学N','大学O','大学P','大学Q',
                    '大学R','大学S','大学T','大学U','大学V','大学W','大学X','大学Y','大学Z'],
      academyListOptions:['计算机学院','土木学院','机械学院','经济管理学院','法学院','医学院',
                    '体育学院','电气与工程学院','核学院','语言文学学院','建筑学院','设计学院'],
      majorListOptions: ['专业a','专业b','专业c','专业d','专业e','专业f','专业g','专业h',
                  '专业i','专业j','专业k','专业l','专业m','专业n','专业o','专业p','专业q',
                  '专业r','专业s','专业t','专业u','专业v','专业w','专业X','专业y','专业z'],
      gradeOptions: [18,19,20,21,22,23,24],
      classOptions: [1,2,3,4,5,6,7,8,9,10],
      provinceOptions: ['北京','天津','上海','重庆','香港','澳门','台湾','河北','山西','辽宁','吉林','黑龙江',
                    '江苏','浙江','安徽','福建','江西','山东','河南','湖北','湖南','广东','海南','四川','贵州',
                    '云南','陕西','甘肃','青海','内蒙古','广西','西藏','宁夏','新疆'],
      temp: {
        id: undefined,
        name: '',
        sno:'',
        school:'',
        academy:'',
        major:'',
        grade:'',
        myclass:'',
        id_number:'',
        admission_number:'',
        points: '',
        state: 'inactive',//默认状态：未激活
        image:'',//头像
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      rules: {
        points: [{ required: true, message: 'point is required', trigger: 'blur' }],
        name: [{ required: true, message: 'name is required', trigger: 'blur' }],
        sno: [{ required: true, message: 'sno is required', trigger: 'blur' }],
        school: [{ required: true, message: 'school is required', trigger: 'blur' }],
        id_number: [{ required: true, message: 'id_number is required', trigger: 'blur' }],
        admission_number: [{ required: true, message: 'admission_number is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getStudentList()
  },
  methods: {
    getStudentList() {
      this.listLoading = true
      fetchStudentList(this.listQuery).then(response => {
        this.list = response.data.rows
        this.total = response.data.total

        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    
    handleFilter() {
      this.listQuery.page = 1
      this.getStudentList()
    },
    handleModifystate(row, state) {
      this.$message({
        message: '操作Success',
        type: '1'
      })
      row.state = state
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        update_time: new Date(),
        name: '',
        state: 'inactive',
        type: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createStudentData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          this.temp.author = 'XinMiao_MS'
          createStudent(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.update_time = new Date(this.temp.update_time)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateStudentData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.update_time = +new Date(tempData.update_time)
          updateStudent(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['id','name', 'type', 'point', 'status','operator','operateTime']
        const filterVal = ['id', 'name', 'type', 'points', 'state','update_user','update_time']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'update_time') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>